package com.java.concurrency.main;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.java.concurrency.Query;
import com.java.concurrency.QueryExecutor;
import com.java.concurrency.QueryResult;
import com.java.concurrency.db.DBConnection;
/**
 * Actual Program will start here
 * static block used to initalize database table.
 * @author managanesh
 *
 */
public class Main {

	private static int NTHREADS = Runtime.getRuntime().availableProcessors();
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);

		List<Future<QueryResult>> list = new ArrayList<Future<QueryResult>>();
		List <Query>qList = new ArrayList<Query>();
		//TODO: here set the list of query objects you need to execute.
		
		
		for(Query query:qList){
			Callable<QueryResult> worker = new QueryExecutor(query);
			Future<QueryResult> submit = executor.submit(worker);
			list.add(submit);
		}	
		
		for (Future<QueryResult> future : list) {
			try {
				QueryResult resutl=future.get();
				//TODO use what ever you want todo here.
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		
		executor.shutdown();

	}
	
	static {
		try{
		//Database setup
    	boolean logTableFound = false;
    
    		Connection logConnection = DBConnection.getConnection();
    		ResultSet logTableSet = logConnection.getMetaData().getTables(null, null, "log", null);
    		
    		while (logTableSet.next()) { 
    		 if("log".equals(logTableSet.getString(3))){
    			 logTableFound = true;
    		 }
    		} 
    		
    		if(!logTableFound){
    			Statement logStat = logConnection.createStatement();
    			//need to change this create query to specific DB create query
    			logStat.executeUpdate("CREATE TABLE public.log(" +
    									"message VarChar(100)," +
    									"level CHAR(20)," +
    									"date Char(50)" +
    									") ") ;/*+
    									"WITH (   OIDS=FALSE )");*/
    			logStat.executeUpdate("GRANT ALL ON TABLE log TO public");

    			System.out.println("need to create table");
    		}
		}catch(Exception e){
			throw new RuntimeException("Initialization exception",e);
		}
	}

}
